
import { globalUtils } from '../../common/js/global-utils/global-utils-all';
import { uiUtils } from '../../common/js/ui-utils/ui-utils-all';
import Pure from 'pure-frontend';
import uiData from 'ui-data';

/* SOURCE-CODE-START */

"use strict";


Pure.app.viewScope('menu-management', function (scope) {
  var jqEditMenuDialog;
  var jqEditMenuForm;
  var jqChooseMenuDialog;
  var jqChooseParentMenuBtn;
  var jqMenuChooseTree;
  var dataModel;

  var menuValidationRule = {
    rules: {
      menuCode: {
        required: true,
        maxlength: 50,
        customCode: true
      },
      menuName: {
        required: true,
        maxlength: 20
      },
      menuIcon: {
        maxlength: 50
      },
      menuPath: {
        required: true,
        maxlength: 500
      },
      menuOrder: {
        required: true,
        digits: true
      },
      remark: {
        maxlength: 200
      }
    },
    messages: {
      menuCode: {
        required: '${t("ui.menu.common.validation.menuCodeRequired")}'
      },
      menuName: {
        required: '${t("ui.menu.common.validation.menuNameRequired")}'
      },
      menuPath: {
        required: '${t("ui.menu.common.validation.menuPathRequired")}',
      },
      menuOrder: {
        required: '${t("ui.menu.common.validation.menuOrderRequired")}'
      }
    }
  };

  scope.showEditMenuDialog = function (view, menuData) {
    if (globalUtils.isNullOrUndefined(jqEditMenuDialog)) {
      jqEditMenuDialog = view.$ui('editMenuDialog');
      jqEditMenuForm = jqEditMenuDialog.find('form');
      jqChooseMenuDialog = view.$ui('chooseMenuDialog');
      jqChooseParentMenuBtn = view.$ui('chooseParentMenuBtn');
      jqMenuChooseTree = view.$ui('menuChooseTree');
      dataModel = view.getDataModel();

      // 添加校验规则
      jqEditMenuForm.validate(menuValidationRule);

      // 添加对话框事件
      addDialogEvent(view);
    }

    // 显示弹出框
    uiUtils.dialog.showModal(jqEditMenuDialog, view, {
      backdropParent: view.getViewElement(),
      onModalShow: function () {
        // 初始对话框数据
        var data = uiData.utils.prefix(menuData, 'edit.');
        dataModel.setData('edit.*', data);

        uiUtils.view.checkFormDataChangeWhenLeave(scope, getDialogData);
      },
      onModalHide: function () {
        uiUtils.common.resetValidation(jqEditMenuForm);
      }
    });
  };

  /**
   * 添加对话框事件
   * @param {View} view 
   */
  function addDialogEvent(view) {
    jqEditMenuDialog.on(uiUtils.event.MODAL_HIDE, function () {
      uiUtils.view.notCheckFormDataChangeWhenLeave(scope);
    });

    // 点击上级菜单的选择按钮后弹出选择菜单的对话框
    jqChooseParentMenuBtn.on(uiUtils.event.CLICK, function () {
      // 
      uiUtils.dialog.showModal(jqChooseMenuDialog, {
        backdropParent: view.getViewElement(),
        onModalShow: function () {
          // 加载树形控件的数据
          loadMenuChooseTreeData(view);
        }
      });
    });

    jqChooseMenuDialog.on(uiUtils.event.MODAL_HIDE, function () {
      // 重置树形控件
      uiUtils.tree.destroy(jqMenuChooseTree);
    });

    jqChooseMenuDialog.on(uiUtils.event.CLICK, uiUtils.dialog.BTN_CONFIRM, function () {
      updateParentMenuFields();
    });

    // 点击"编辑菜单"对话框的保存按钮后调用接口更新菜单
    jqEditMenuDialog.on(uiUtils.event.CLICK, uiUtils.dialog.BTN_CONFIRM, function () {
      var checkResult = jqEditMenuForm.valid();
      if (!checkResult) {
        return;
      }

      var updateData = dataModel.getData('edit.*');
      updateData = uiData.utils.unprefix(updateData, 'edit.');

      // 调用更新记录的接口
      view.callService('api/menu/menu/updateMenu', updateData)
        .waitResult(function (result) {
          if (result.success) {
            uiUtils.dialog.hideModal(jqEditMenuDialog);
            scope.refreshTreeMenuStructure();
            Pure.app.showMessage('${t("ui.system.common.msg.saveRecordSuccess")}');
          } else {
            Pure.app.showError(result.message);
          }
        });
    });
  }

  // 返回对话框的数据
  function getDialogData() {
    return dataModel.getData('edit.*');
  }

  /**
   * 更新上级菜单字段
   */
  function updateParentMenuFields() {
    var nodes = uiUtils.tree.getSelectedNodes(jqMenuChooseTree);
    var parentId = '';
    var parentName = '';

    if (nodes.length > 0) {
      var nodeInfo = nodes[0].original.nodeInfo;

      if (nodeInfo.type === 'menu') {
        var menuData = nodeInfo.data;
        parentId = menuData.id;
        parentName = menuData.menuName;
      }
    }

    // 设置上级菜单
    dataModel.setData(['edit.parentId', 'edit.parentName'], {
      'edit.parentId': parentId,
      'edit.parentName': parentName
    });

    uiUtils.dialog.hideModal(jqChooseMenuDialog);
  }


  /**
   * 设置选择菜单的树形数据
   */
  function setMenuChooseTreeData(treeData) {
    // 渲染树形控件
    uiUtils.tree.init(jqMenuChooseTree, {
      'core': {
        'themes': {
          'icons': true
        },
        'data': treeData
      }
    });
  }

  /**
   * 加载选择菜单的树形数据
   * @param {*} view 
   */
  function loadMenuChooseTreeData(view) {
    var templateId = dataModel.getData('edit.templateId');
    var menuId = dataModel.getData('edit.id');
    var parentId = dataModel.getData('edit.parentId');

    // 加载菜单数据到树形控件
    view.callService('api/menu/menuTemplate/getMenuTemplateById', {
      id: templateId
    }).waitResult(function (result) {
      if (!uiUtils.common.checkWebResultSuccess(result)) {
        return;
      }

      var templateData = result.data;

      view.callService('api/menu/menu/listHierarchyMenus', {
        id: templateData.id
      }).waitResult(function (result) {
        if (result.success) {
          var templateName = templateData.templateName;
          var menuData = result.data;
          // 转换成树形数据
          var treeData = CurrentRunningApp.sharing.menu.convertToTreeData(menuData, function (node, type, data) {
            if (type === 'function') {
              return false;
            }

            if (type === 'menu') {
              if (menuId === data.id) {
                // 不能选中当前的菜单
                node.state.disabled = true;
              } else if (parentId === data.id) {
                // 初始时选中当前菜单的上级菜单
                node.state.selected = true;
              }
            }

            return true;
          });

          var templateNodeId = 'template_' + templateData.id;
          treeData = [{
            id: templateNodeId,
            text: templateName,
            icon: false,
            state: {
              opened: true,
              selected: !globalUtils.isNotEmptyString(parentId)
            },
            children: treeData,
            nodeInfo: {
              type: 'template',
              data: templateData,
              childMenus: menuData
            }
          }];

          // 设置选择菜单的树形数据
          setMenuChooseTreeData(treeData);
        } else {
          Pure.app.showError(result.message);
        }
      });
    });
  }


});

/* SOURCE-CODE-END */


